package com.tsm.picachu.mainmenu.ui;

import com.util.library.sound.SoundPlay;
import com.tsm.picachu.GeneralActivity;
import com.tsm.picachu.R;
import com.tsm.picachu.common.Constant;
import com.tsm.picachu.gameplay.ui.GamePlayActivity;
import com.tsm.picachu.highscore.ui.HighScoreActivity;
import com.tsm.picachu.level.ui.SelectLevelActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

public class MainMenuActivity extends GeneralActivity
{
	private boolean mIsMusicOn = true;
	private Button mButtonBackgroundMusic = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_main_menu);

		final String username = getIntent().getStringExtra(
				Constant.EXTRA_USERNAME);

		((ImageButton) findViewById(R.id.button_play)).setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				Intent intent = new Intent(MainMenuActivity.this,
						GamePlayActivity.class);
				intent.putExtra(Constant.EXTRA_USERNAME, username);
				startActivity(intent);
			}
		});

		mButtonBackgroundMusic = (Button) findViewById(R.id.button_music);

		final SharedPreferences sharedPreferences = getSharedPreferences(
				Constant.PREFERENCE_SETTINGS, MODE_PRIVATE);
		mIsMusicOn = sharedPreferences.getBoolean(Constant.PREFERENCE_MUSIC,
				true);
		playBackgroundMusic();

		mButtonBackgroundMusic.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				mIsMusicOn = !mIsMusicOn;
				playBackgroundMusic();
				if (!mIsMusicOn)
				{
					SoundPlay.stop();
				}
				Editor editor = sharedPreferences.edit();
				editor.putBoolean(Constant.PREFERENCE_MUSIC, mIsMusicOn);
				editor.commit();
			}
		});

		((Button) findViewById(R.id.menu_high_score)).setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				startActivity(HighScoreActivity.class);
			}
		});

		((Button) findViewById(R.id.menu_quit)).setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				SoundPlay.stop();
				finish();
			}
		});

		((Button) findViewById(R.id.menu_select_level)).setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				Intent intent = new Intent(MainMenuActivity.this,
						SelectLevelActivity.class);
				intent.putExtra(Constant.EXTRA_USERNAME, username);
				startActivity(intent);
			}
		});
	}

	private void playBackgroundMusic()
	{
		if (mIsMusicOn)
		{
			mButtonBackgroundMusic.setBackgroundResource(R.drawable.music_on);
			SoundPlay.play(getApplicationContext(), Constant.SOUND_BG, -1);
		}
		else
		{
			mButtonBackgroundMusic.setBackgroundResource(R.drawable.music_off);
		}
	}
}